/**
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY. See the GNU General Public License for more details. Copyright (C) 2011 CellObject.net
 */
package net.cellobject.sqlitexmlbrowser.xmlopener;

import java.io.File;

import net.cellobject.sqlitexmlbrowser.SQLiteXMLBrowserPluginStartup;
import net.cellobject.sqlitexmlbrowser.shared.DeviceExplorerAccessor;
import net.cellobject.sqlitexmlbrowser.shared.Logger;

import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.Path;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.IDE;
import com.android.ddmlib.FileListingService.FileEntry;
import com.android.ddmuilib.explorer.DeviceExplorer;

public class XmlOpener {
	public static void openXmlFile(final IWorkbenchPage page, final DeviceExplorer mExplorer, final FileEntry fileEntry) {
		// Write .xml file to a temp file
		final String defaultPath = System.getProperty("user.home");
		final String tempXmlFilePath = defaultPath + File.separator + fileEntry.getName();
		//Close any open editor with the old file to avoid the warning dialog box "file changed in the file system" when trying to open the same file again
		closeCurrentXmlEditor(page, fileEntry.getName());
		//Must delete existing file before pulling new file!
		DeviceExplorerAccessor.pullFile(mExplorer, fileEntry, tempXmlFilePath);
		//
		final IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(tempXmlFilePath));
		if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
			try {
				IDE.openEditorOnFileStore(page, fileStore);
				//Enable button again
				SQLiteXMLBrowserPluginStartup.devToolsFileOpenerAction.setEnabled(true);
			} catch (final PartInitException e) {
				Logger.logInfo("Error when opening Xml file..");
			}
		}
	}

	/**
	 * Close any open editor with the old file to avoid the warning dialog box "file changed in the file system" when trying to
	 * open the same file again.
	 */
	private static void closeCurrentXmlEditor(final IWorkbenchPage page, final String tempXmlFileName) {
		final IEditorReference[] editors = page.getEditorReferences();
		if (editors != null) {
			for (final IEditorReference reference : editors) {
				if (reference.getTitle().equalsIgnoreCase(tempXmlFileName)) {
					final IEditorPart editorPart = reference.getEditor(false);
					page.closeEditor(editorPart, true);
				}
			}
		}
	}
}
